import { _decorator, Component, instantiate, Node, Prefab, resources, v3 } from 'cc';
import { RoleBase } from '../Item/Role/RoleBase';
import EventManager from '../Util/EventManager';
import { EventMsg } from './GlobalContext';

export default class ObjPool{
    private static _instance: ObjPool = null;
    static get inst(): ObjPool{
        if(this._instance == null){
            this._instance = new ObjPool();
        }
        return this._instance;
    }

    private _roles: Map<string, Array<Node>> = null;

    initRoles(path: string = 'prefabs', count: number = 20): void{
        this._roles = new Map<string, Array<Node>>();
        let self = this;
        resources.loadDir(path, Prefab, function (err, assets) {
            if (err) {
                console.error('loadDir error:', err);
                return;
            }

            let len: number = assets.length;
            let complete: number = 0;
            assets.forEach(prefab=>{
                let roles: Array<Node> = new Array<Node>();
                for(let i = 0; i < count; i++) {
                    const roleNode: Node = instantiate(prefab);
                    roleNode.active = false;
                    roleNode.position = v3(0, 0, 0);
                    roles.push(roleNode);
                }
                self._roles.set(prefab.name, roles);
                complete++;
                if(complete == len){
                    EventManager.getInst().Trigger(EventMsg.INIT_ROLR_COMPLE);
                }
            });
        });
    }

    getRoleNode(role: string): Node{
        if(this._roles.has(role)){
            let roles = this._roles.get(role);
            if(roles.length == 0)
                return null;
            const roleNode: Node = roles.pop();
            this._roles.set(role, roles);
            roleNode.active = true;
            return roleNode;
        }else{
            return null;
        }
    }

    putRoleNode(role: string, roleNode: Node): void{
        if(this._roles.has(role)){
            let roles = this._roles.get(role);
            roleNode.parent = null;
            roleNode.active = false;
            roleNode.position = v3(0, 0, 0);
            roles.push(roleNode);
            this._roles.set(role, roles);
        }
    }
}